package com.eastmoney.emis.edda.task;

import com.eastmoney.emis.edda.task.handler.TaskHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.Executor;

/**
 * @description: Description
 * @projectName: EDDA-HSBC
 * @package: com.eastmoney.emis.edda.task
 * @author: 汪程程
 * @date: 2022/10/10 1:20 PM
 * @version: 1.0
 */
@Component
public class TaskManagement {
    private static Logger log = LoggerFactory.getLogger(TaskManagement.class);

    //private Set<String> taskSet = new ConcurrentSkipListSet<>();
    @Autowired
    private Map<String, TaskHandler> taskHandlerMap;
    private final Executor executor;

    private final TaskContainer taskContainer;

    public TaskManagement(Executor eddaTaskExecutor, TaskContainer taskContainer) {
        this.executor = eddaTaskExecutor;
        this.taskContainer = taskContainer;
    }

    public synchronized void addTask(AbstractTask task) {
        if (!taskContainer.addTask(task.getId())) {
            log.info("该任务正在队列中, 请稍后查看结果, [id={}, name={}]", task.getId(), task.getName());
            return;
        }
        Runnable runnable = () -> {
            try {
                TaskHandler<AbstractTask> taskHandler = taskHandlerMap.get(task.getName() + "Handler");
                if (taskHandler == null) {
                    log.warn("Unknown task name, please check task = [{}]", task);
                    return;
                }
                taskHandler.handle(task);
            } finally {
                taskContainer.removeTask(task.getId());
            }
        };
        executor.execute(runnable);
    }

}
